using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

public static class EnhancedEditorUtils
{
    // 存储临时折叠状态的字典（当前会话）
    private static Dictionary<string, bool> foldoutStates = new Dictionary<string, bool>();
    // 跟踪已保存的键
    private static HashSet<string> savedKeys = new HashSet<string>();
    // 用于生成唯一标识的基础前缀
    private static string uniqueIdPrefix;
    
    // 样式缓存
    private static GUIStyle headerStyle;
    private static GUIStyle headerLabelStyle;
    private static GUIStyle contentAreaStyle;
    
    // 颜色配置
    private static readonly Color headerNormal = new Color(0.1f, 0.1f, 0.1f);
    private static readonly Color headerActive = new Color(0.2f, 0.4f, 0.6f);
    private static readonly Color contentBg = new Color(0.18f, 0.18f, 0.18f);
    private static readonly Color borderColorNormal = new Color(0.1f, 0.1f, 0.1f);
    private static readonly Color borderColorHover = new Color(0.1f, 0.1f, 0.1f);
    private static readonly Color borderColorActive = new Color(0.15f, 0.15f, 0.15f);
    private static readonly Color activeTextColor = new Color(1f, 1f, 1f);
    private static readonly Color normalTextColor = new Color(0.9f, 0.9f, 0.9f);

    // 纹理缓存池 - 避免重复创建纹理
    private static Dictionary<Color, Texture2D> colorTextures = new Dictionary<Color, Texture2D>();
    // 图标字符串缓存
    private static readonly string expandedIcon = "   ▼";
    private static readonly string collapsedIcon = "   ►";

    static EnhancedEditorUtils()
    {
        uniqueIdPrefix = $"{typeof(EnhancedEditorUtils).FullName}_";
        LoadFoldoutStates();
        // 预创建常用纹理
        PrecreateTextures();
    }

    /// <summary>
    /// 预创建常用纹理避免运行时频繁创建
    /// </summary>
    private static void PrecreateTextures()
    {
        GetOrCreateColorTexture(headerNormal);
        GetOrCreateColorTexture(headerActive);
        GetOrCreateColorTexture(contentBg);
        GetOrCreateColorTexture(borderColorNormal);
        GetOrCreateColorTexture(borderColorHover);
        GetOrCreateColorTexture(borderColorActive);
        GetOrCreateColorTexture(activeTextColor);
        GetOrCreateColorTexture(normalTextColor);
    }
    
    /// <summary>
    /// 绘制无箭头的自定义折叠框标题，状态会持久化保存
    /// </summary>
    public static bool DrawHeaderFoldout(string groupName, bool defaultState)
    {
        InitializeStyles();

        string uniqueKey = $"{uniqueIdPrefix}{groupName}";

        // 延迟初始化状态，只在需要时执行
        if (!foldoutStates.ContainsKey(uniqueKey))
        {
            bool savedState = EditorPrefs.HasKey(uniqueKey) ? EditorPrefs.GetBool(uniqueKey) : defaultState;
            foldoutStates[uniqueKey] = savedState;
            
            if (!savedKeys.Contains(uniqueKey))
            {
                savedKeys.Add(uniqueKey);
            }
        }

        bool isExpanded = foldoutStates[uniqueKey];
        // 使用缓存的纹理
        headerStyle.normal.background = GetOrCreateColorTexture(isExpanded ? borderColorActive : borderColorNormal);
        headerStyle.hover.background = GetOrCreateColorTexture(isExpanded ? borderColorActive : borderColorHover);
        headerLabelStyle.normal.textColor = isExpanded ? activeTextColor : normalTextColor;

        // 绘制头部背景
        Rect headerRect = EditorGUILayout.BeginHorizontal(headerStyle);
        GUILayout.Space(5);

        // 绘制展开/折叠图标（使用缓存字符串）
        EditorGUILayout.LabelField(isExpanded ? expandedIcon : collapsedIcon, headerLabelStyle, GUILayout.Width(30));

        // 绘制标题文本
        EditorGUILayout.LabelField(groupName, headerLabelStyle);

        EditorGUILayout.EndHorizontal();

        // 检测点击事件（只在鼠标按下时处理）
        if (Event.current.type == EventType.MouseDown && headerRect.Contains(Event.current.mousePosition))
        {
            foldoutStates[uniqueKey] = !foldoutStates[uniqueKey];
            isExpanded = foldoutStates[uniqueKey];
            SaveFoldoutState(uniqueKey, isExpanded);
            Event.current.Use();
        }

        // 绘制装饰性边框
        DrawHeaderBorder(headerRect, isExpanded);

        return isExpanded;
    }
    
    /// <summary>
    /// 开始绘制折叠内容区域
    /// </summary>
    public static void BeginFoldoutContent()
    {
        Rect contentRect = EditorGUILayout.BeginVertical(contentAreaStyle);
        // 只在需要时绘制背景（避免重复绘制）
        if (contentAreaStyle.normal.background != null)
        {
            GUI.Box(contentRect, GUIContent.none, contentAreaStyle);
        }
        EditorGUI.indentLevel += 1;
    }
    
    /// <summary>
    /// 结束绘制折叠内容区域
    /// </summary>
    public static void EndFoldoutContent()
    {
        EditorGUI.indentLevel -= 1;
        EditorGUILayout.EndVertical();
    }
    
    // 初始化样式（只执行一次）
    private static void InitializeStyles()
    {
        if (headerStyle != null) return; // 已初始化则直接返回

        headerStyle = new GUIStyle
        {
            fixedHeight = 26f,
            padding = new RectOffset(5, 5, 3, 3),
            margin = new RectOffset(0, 0, 4, 0)
        };
        
        headerLabelStyle = new GUIStyle
        {
            fontStyle = FontStyle.Bold,
            fontSize = 14,
            alignment = TextAnchor.MiddleLeft,
            stretchWidth = true,
            clipping = TextClipping.Overflow,
            hover = { textColor = Color.white } // 提前设置hover状态
        };
        
        contentAreaStyle = new GUIStyle
        {
            normal = { background = GetOrCreateColorTexture(contentBg) },
            padding = new RectOffset(15, 15, 8, 8),
            margin = new RectOffset(0, 0, 0, 6)
        };
    }
    
    // 绘制头部边框
    private static void DrawHeaderBorder(Rect rect, bool isExpanded)
    {
        var targetColor = isExpanded ? headerActive : headerNormal;
        Rect leftBar = new Rect(rect.x, rect.y, 10, rect.height);
        GUI.DrawTexture(leftBar, GetOrCreateColorTexture(targetColor));
    }
    
    /// <summary>
    /// 获取或创建颜色纹理（使用缓存避免重复创建）
    /// </summary>
    private static Texture2D GetOrCreateColorTexture(Color color)
    {
        // 检查缓存中是否存在
        if (colorTextures.TryGetValue(color, out Texture2D existing))
        {
            return existing;
        }

        // 不存在则创建并缓存
        Texture2D tex = new Texture2D(1, 1, TextureFormat.ARGB32, false)
        {
            hideFlags = HideFlags.DontSave // 标记为不保存到资源
        };
        tex.SetPixel(0, 0, color);
        tex.Apply();
        colorTextures[color] = tex;
        return tex;
    }
    
    /// <summary>
    /// 清除指定组的状态缓存（包括持久化存储）
    /// </summary>
    public static void ClearFoldoutState(string groupName)
    {
        string targetKey = $"{uniqueIdPrefix}{groupName}";
        // 使用数组避免枚举时修改集合
        string[] keysToRemove = System.Array.Empty<string>();
        
        lock (foldoutStates)
        {
            keysToRemove = new string[foldoutStates.Count];
            foldoutStates.Keys.CopyTo(keysToRemove, 0);
        }
        
        foreach (var key in keysToRemove)
        {
            if (key == targetKey || key.StartsWith($"{targetKey}_"))
            {
                foldoutStates.Remove(key);
                savedKeys.Remove(key);
                EditorPrefs.DeleteKey(key);
            }
        }
    }

    /// <summary>
    /// 清除所有折叠状态（包括持久化存储）
    /// </summary>
    public static void ClearAllFoldoutStates()
    {
        foldoutStates.Clear();
        
        // 清除所有相关的EditorPrefs
        foreach (var key in savedKeys)
        {
            EditorPrefs.DeleteKey(key);
        }
        savedKeys.Clear();
    }

    // 从EditorPrefs加载所有状态
    private static void LoadFoldoutStates()
    {
        foldoutStates.Clear();
        savedKeys.Clear();
    }

    // 保存单个状态到EditorPrefs
    private static void SaveFoldoutState(string key, bool state)
    {
        EditorPrefs.SetBool(key, state);
        
        if (!savedKeys.Contains(key))
        {
            savedKeys.Add(key);
        }
    }
}